package com.bestcem.xm.ticket.grpc.client.convert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.bp.xm.user.grpc.v1.services.*;
import com.bestcem.xm.ticket.grpc.client.dto.user.*;
import com.bestcem.xm.user.grpc.v1.common.IdRelation;
import com.google.protobuf.util.Timestamps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * TicketBaseUserGrpcService 中 response 转 DTO
 *
 * @author ympan <yuming.pan@idiaoyan.com>
 * @version v1.0
 * @date 2021/8/26 17:59
 */
public class TicketBaseUserConvert {

    private TicketBaseUserConvert() {
    }

    /**
     * User to UserDTO
     *
     * @param user User
     * @return UserDTO
     * @author XiaoYunSong <ys.xiao@idiaoyan.cn>
     * @date 2021/8/2 14:40
     */
    public static UserDTO toUserDTO(User user) {
        if (Objects.isNull(user)) {
            return null;
        }
        UserDTO userDTO = new UserDTO();
        userDTO.setId(user.getId());
        userDTO.setOrgId(user.getOrgId());
        userDTO.setUserName(user.getUsername());
        userDTO.setPassword(user.getPassword());
        userDTO.setSalt(user.getSalt());
        userDTO.setName(user.getName());
        userDTO.setAvatar(user.getAvatar());
        userDTO.setEmail(user.getEmail());
        userDTO.setMobile(user.getPhone());
        userDTO.setStatus(user.getStatus().getNumber());
        userDTO.setContent(user.getContent());
        userDTO.setEdition(user.getEdition().getNumber());
        userDTO.setShowIntroduction(user.getShowGuide());
        userDTO.setWxUnionid(user.getWxInfo().getUnionId());
        userDTO.setWxOpenid(user.getWxInfo().getMiniOpenId());
        userDTO.setWxOffiOpenid(user.getWxInfo().getOffiOpenId());
        userDTO.setWxNickname(user.getWxInfo().getNickname());
        userDTO.setFsOpenId(user.getFsInfo().getOpenId());
        userDTO.setFsUnionId(user.getFsInfo().getUnionId());
        userDTO.setFsName(user.getFsInfo().getName());
        userDTO.setSsoName(user.getSsoName());
        userDTO.setIsAccept(user.getAccept());
        userDTO.setLastLoginTime(Instant.ofEpochMilli(Timestamps.toMillis(user.getLastLoginTime())).atZone(ZoneOffset.of("+8")).toLocalDateTime());
        userDTO.setRegisterIp(user.getRegisterIp());
        userDTO.setIsInnerUser(user.getInner());
        userDTO.setGuide(user.getGuideRecordsList());
        return userDTO;
    }

    /**
     * List<UserRole> to List<UserRoleDTO>
     *
     * @param infoList List<UserRole>
     * @return UserRoleDTO
     * @author XiaoYunSong <ys.xiao@idiaoyan.cn>
     * @date 2021/11/4 20:26
     */
    @Nonnull
    public static List<UserRoleDTO> toUserRoleDTOList(List<UserRole> infoList) {
        List<UserRoleDTO> dtoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(infoList)) {
            for (UserRole info : infoList) {
                UserRoleDTO dto = toUserRoleDTO(info);
                if (Objects.nonNull(dto)) {
                    dtoList.add(dto);
                }
            }
        }
        return dtoList;
    }

    /**
     * UserRole to UserRoleDTO
     *
     * @param info UserRole
     * @return UserRoleDTO
     * @author XiaoYunSong <ys.xiao@idiaoyan.cn>
     * @date 2021/11/4 20:26
     */
    @Nullable
    public static UserRoleDTO toUserRoleDTO(UserRole info) {
        if (Objects.isNull(info)) {
            return null;
        }
        UserRoleDTO dto = new UserRoleDTO();
        dto.setId(info.getId());
        dto.setUserId(info.getUserId());
        dto.setRoleId(info.getRoleId());
        return dto;
    }

    /**
     * UserList to List<UserDTO>
     *
     * @param users UserList
     * @return List<UserDTO>
     * @author XiaoYunSong <ys.xiao@idiaoyan.cn>
     * @date 2021/8/2 14:40
     */
    public static List<UserDTO> toUserDTOList(List<User> users) {
        List<UserDTO> userDTOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(users)) {
            for (User user : users) {
                UserDTO userDTO = toUserDTO(user);
                if (Objects.nonNull(userDTO)) {
                    userDTOList.add(userDTO);
                }
            }
        }
        return userDTOList;
    }

    /**
     * Group to GroupDTO
     *
     * @param group proto中定义的Group
     * @return 成员组DTO
     * @author <yuming.pan@idiaoyan.com>
     * @date 21:11 2021/8/26
     */
    public static GroupDTO toGroupDTO(Group group) {
        if (Objects.isNull(group)) {
            return null;
        }
        GroupDTO groupDTO = new GroupDTO();
        groupDTO.setId(group.getId());
        groupDTO.setAncestors(group.getParentIdsList());
        groupDTO.setParentId(group.getParentId());
        groupDTO.setRootId(group.getRootId());
        groupDTO.setRoot(group.getRoot());
        groupDTO.setOrgId(group.getOrgId());
        groupDTO.setCode(group.getCode());
        groupDTO.setSeq(group.getSeq());
        groupDTO.setTitle(group.getName());
        groupDTO.setGroupType(group.getTypeValue());
        groupDTO.setGroupLevelId(group.getLevelId());
        groupDTO.setStatus(group.getStatusValue());
        groupDTO.setContact(group.getPhone());
        groupDTO.setEmail(group.getEmail());
        groupDTO.setAdminId(group.getAdminId());
        groupDTO.setAdminName(group.getAdminName());
        return groupDTO;
    }

    /**
     * GroupLevel to GroupLevelDTO
     *
     * @param groupLevel GroupLevel
     * @return 成员组层级DTO
     * @author <yuming.pan@idiaoyan.com>
     * @date 11:15 2021/8/27
     */
    public static GroupLevelDTO toGroupLevelDTO(GroupLevel groupLevel) {
        if (Objects.isNull(groupLevel)) {
            return null;
        }
        GroupLevelDTO groupLevelDTO = new GroupLevelDTO();
        groupLevelDTO.setId(groupLevel.getId());
        groupLevelDTO.setOrgId(groupLevel.getOrgId());
        groupLevelDTO.setTitle(groupLevel.getName());
        groupLevelDTO.setNxtId(groupLevel.getChildrenId());
        groupLevelDTO.setLevel(groupLevel.getLevel());
        groupLevelDTO.setDisplay(groupLevel.getDisplay());
        return groupLevelDTO;
    }

    /**
     * Organization to OrganizationDTO
     *
     * @param org 单个Organization
     * @return 组织DTO
     * @author <yuming.pan@idiaoyan.com>
     * @date 13:56 2021/8/27
     */
    public static OrganizationDTO toOrganizationDTO(Organization org) {
        if (Objects.isNull(org)) {
            return null;
        }
        OrganizationDTO organizationDTO = new OrganizationDTO();
        organizationDTO.setId(org.getId());
        organizationDTO.setCode(org.getCode());
        organizationDTO.setName(org.getName());
        organizationDTO.setContent(org.getContent());
        organizationDTO.setStatus(org.getStatusValue());
        organizationDTO.setSource(org.getSourceValue());
        organizationDTO.setSourceRemark(org.getSourceRemark());
        organizationDTO.setRootGroupId(org.getRootGroupId());
        organizationDTO.setIndustryId(org.getIndustryId());
        organizationDTO.setPackageId(org.getPackageId());
        organizationDTO.setFormalPackageId(org.getFormalPackageId());
        if (Objects.nonNull(org.getFormalExpireTime())) {
            organizationDTO.setFormalExpiryDateTime(Instant.ofEpochMilli(Timestamps.toMillis(org.getFormalExpireTime())).atZone(ZoneOffset.of("+8")).toLocalDateTime());
        }
        organizationDTO.setTrialPackageId(org.getTrialPackageId());
        if (Objects.nonNull(org.getTrialExpireTime())) {
            organizationDTO.setTrialExpiryDateTime(Instant.ofEpochMilli(Timestamps.toMillis(org.getTrialExpireTime())).atZone(ZoneOffset.of("+8")).toLocalDateTime());
        }
        organizationDTO.setEmail(org.getAdminEmail());
        organizationDTO.setMobile(org.getAdminPhone());
        if (Objects.nonNull(org.getPackageExpireTime())) {
            organizationDTO.setExpiryDateTime(Instant.ofEpochMilli(Timestamps.toMillis(org.getPackageExpireTime())).atZone(ZoneOffset.of("+8")).toLocalDateTime());
        }
        if (Objects.nonNull(org.getFreeExpireTime())) {
            organizationDTO.setFreeExpiryDateTime(Instant.ofEpochMilli(Timestamps.toMillis(org.getFreeExpireTime())).atZone(ZoneOffset.of("+8")).toLocalDateTime());
        }
        String skin = org.getSkin();
        if (StringUtils.isNotEmpty(skin)) {
            JSONObject skinObj = JSON.parseObject(skin);
            OrganizationDTO.Skin skin1 = new OrganizationDTO.Skin();
            skin1.setStatus(String.valueOf(skinObj.get("status")));
            skin1.setHideLoginChanger((Boolean) skinObj.get("hideLoginChanger"));
            skin1.setHideUserCenter((Boolean) skinObj.get("hideUserCenter"));
            skin1.setLoginColor(String.valueOf(skinObj.get("loginColor")));
            skin1.setName(String.valueOf(skinObj.get("name")));
            skin1.setTitle(String.valueOf(skinObj.get("title")));
            organizationDTO.setSkin(skin1);
        }
        organizationDTO.setPublicKey(org.getPubFilePath());
        organizationDTO.setPrivateKeyId(org.getPriId());
        organizationDTO.setDeliverCheck(org.getDeliverAudit());
        organizationDTO.setComplete(org.getComplete());
        organizationDTO.setOrgAdmin(org.getAdminName());
        organizationDTO.setCorporateWallet(org.getWalletId());
        organizationDTO.setSmsPrice(org.getSmsPrice());
        organizationDTO.setFooter(org.getFooterValue());
        organizationDTO.setCheckSmtpId(org.getAuditSmtpId());
        organizationDTO.setHasNotifySales(org.getNotifySales());
        organizationDTO.setInner(org.getInner());
        organizationDTO.setPaasConf(org.getPaasConf());
        return organizationDTO;
    }

    /**
     * Role to RoleDTO
     *
     * @param role proto中定义的Role
     * @return 角色DTO
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2022/6/13 18:26
     */
    public static RoleDTO toRoleDTO(Role role) {
        if (Objects.isNull(role)) {
            return null;
        }
        RoleDTO roleDTO = new RoleDTO();
        roleDTO.setId(role.getId());
        roleDTO.setOrgId(role.getOrgId());
        roleDTO.setTitle(role.getName());
        roleDTO.setStatus(role.getStatusValue());
        roleDTO.setRoleType(role.getTypeValue());
        roleDTO.setContent(role.getContent());
        roleDTO.setRoleIndex(role.getIndexValue());
        roleDTO.setBiShare(role.getBiShare());
        return roleDTO;
    }

    /**
     * roleList to List<RoleDTO>
     *
     * @param roleList roleList
     * @return 角色DTO集合
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2022/6/13 18:28
     */
    public static List<RoleDTO> toRoleDTOList(List<Role> roleList) {
        List<RoleDTO> roleDTOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(roleList)) {
            roleList.forEach(role -> {
                if (Objects.nonNull(role)) {
                    RoleDTO roleDTO = toRoleDTO(role);
                    roleDTOList.add(roleDTO);
                }
            });
        }
        return roleDTOList;
    }

    /**
     * smtpList to  List<SmtpDTO>
     *
     * @param smtpList smtpList
     * @return 邮箱设置DTO集合
     * @author <yuming.pan@idiaoyan.com>
     * @date 15:47 2021/8/27
     */
    public static List<SmtpDTO> toSmtpDTOList(List<Smtp> smtpList) {
        List<SmtpDTO> smtpDTOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(smtpList)) {
            smtpList.forEach(smtp -> {
                if (Objects.nonNull(smtp)) {
                    SmtpDTO smtpDTO = toSmtpDTO(smtp);
                    smtpDTOList.add(smtpDTO);
                }
            });
        }
        return smtpDTOList;
    }

    /**
     * Smtp to SmtpDTO
     *
     * @param smtp proto中定义的Smtp
     * @return 邮箱设置DTO
     * @author <yuming.pan@idiaoyan.com>
     * @date 15:49 2021/8/27
     */
    public static SmtpDTO toSmtpDTO(Smtp smtp) {
        if (Objects.isNull(smtp)) {
            return null;
        }
        SmtpDTO smtpDTO = new SmtpDTO();
        smtpDTO.setId(smtp.getId());
        smtpDTO.setOrgId(smtp.getOrgId());
        smtpDTO.setAccount(smtp.getAccount());
        smtpDTO.setPassword(smtp.getPassword());
        smtpDTO.setHost(smtp.getHost());
        smtpDTO.setPort(String.valueOf(smtp.getPort()));
        smtpDTO.setSSL(smtp.getSsl());
        smtpDTO.setDescription(smtp.getDescription());
        smtpDTO.setMailFrom(smtp.getSenderName());
        smtpDTO.setValidateStatus(smtp.getStatusValue());
        smtpDTO.setDeliver(smtp.getDeliver());
        smtpDTO.setNotice(smtp.getNotice());
        smtpDTO.setSystem(smtp.getSystem());
        return smtpDTO;
    }

    /**
     * userGroupList to List<UserGroupDTO>
     *
     * @param userGroupList userGroupList
     * @return 用户和组的关联集合
     * @author <yuming.pan@idiaoyan.com>
     * @date 16:26 2021/8/27
     */
    public static List<UserGroupDTO> toUserGroupDTOList(List<UserRelateGroup> userGroupList) {
        List<UserGroupDTO> userGroupDTOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userGroupList)) {
            userGroupList.forEach(userRelateGroup -> {
                if (Objects.nonNull(userRelateGroup)) {
                    UserGroupDTO userGroupDTO = toUserGroupDTO(userRelateGroup);
                    userGroupDTOList.add(userGroupDTO);
                }
            });
        }
        return userGroupDTOList;
    }

    /**
     * UserGroup to UserGroupDTO
     *
     * @param userRelateGroup proto中定义的UserRelateGroup
     * @return 用户和组的关联DTO
     * @author <yuming.pan@idiaoyan.com>
     * @date 16:37 2021/8/27
     */
    private static UserGroupDTO toUserGroupDTO(UserRelateGroup userRelateGroup) {
        if (Objects.isNull(userRelateGroup)) {
            return null;
        }
        UserGroupDTO userGroupDTO = new UserGroupDTO();
        userGroupDTO.setId(userRelateGroup.getId());
        userGroupDTO.setRootGroupId(userRelateGroup.getRootGroupId());
        userGroupDTO.setUserId(userRelateGroup.getUserId());
        userGroupDTO.setGroupId(userRelateGroup.getGroupId());
        return userGroupDTO;
    }

    public static List<GroupNodeDTO> groupBaseToGroupNodeDTOList(List<GroupBase> groupBaseList) {
        List<GroupNodeDTO> groupNodeDTOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(groupBaseList)) {
            for (GroupBase groupBase : groupBaseList) {
                GroupNodeDTO groupNodeDTO = toGroupNodeDTO(groupBase);
                if (Objects.nonNull(groupNodeDTO)) {
                    groupNodeDTOList.add(groupNodeDTO);
                }
            }
        }
        return groupNodeDTOList;
    }

    public static GroupNodeDTO toGroupNodeDTO(GroupBase groupBase) {
        if (Objects.isNull(groupBase)) {
            return null;
        }
        GroupNodeDTO groupNodeDTO = new GroupNodeDTO();
        groupNodeDTO.setId(groupBase.getId());
        groupNodeDTO.setSeq(groupBase.getSeq());
        groupNodeDTO.setCode(groupBase.getCode());
        groupNodeDTO.setTitle(groupBase.getName());
        return groupNodeDTO;
    }

    public static GroupNodeDTO toGroupNodeDTO(GroupNode groupNode) {
        if (Objects.isNull(groupNode)) {
            return null;
        }
        GroupNodeDTO groupNodeDTO = new GroupNodeDTO();
        groupNodeDTO.setId(groupNode.getId());
        groupNodeDTO.setSeq(groupNode.getSeq());
        groupNodeDTO.setCode(groupNode.getCode());
        groupNodeDTO.setTitle(groupNode.getName());
        groupNodeDTO.setGroupLevelId(groupNode.getLevelId());
        List<GroupNodeDTO> temp = new ArrayList<>();
        List<GroupNode> childrenList = groupNode.getChildrenList();
        if (!CollectionUtils.isEmpty(childrenList)) {
            for (GroupNode node : childrenList) {
                GroupNodeDTO childNode = toGroupNodeDTO(node);
                if (Objects.nonNull(childNode)) {
                    temp.add(childNode);
                }
            }
        }
        groupNodeDTO.setChildren(temp);

        return groupNodeDTO;
    }

    /**
     * GroupList to GroupDTOList
     *
     * @param groupList proto中定义的Group List
     * @return 成员组DTO List
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/8/30 17:15
     */
    public static List<GroupDTO> toGroupDTOList(List<Group> groupList) {
        List<GroupDTO> groupDTOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(groupList)) {
            for (Group group : groupList) {
                GroupDTO groupDTO = toGroupDTO(group);
                if (Objects.nonNull(groupDTO)) {
                    groupDTOList.add(groupDTO);
                }
            }
        }
        return groupDTOList;
    }

    public static List<IdMapNodeDTO> toIdMapNodeDTOList(List<IdRelation> idRelations) {
        List<IdMapNodeDTO> idMapNodeDTOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(idRelations)) {
            for (IdRelation idRelation : idRelations) {
                IdMapNodeDTO idMapNodeDTO = toIdMapNodeDTO(idRelation);
                if (Objects.nonNull(idMapNodeDTO)) {
                    idMapNodeDTOList.add(idMapNodeDTO);
                }
            }
        }
        return idMapNodeDTOList;
    }

    private static IdMapNodeDTO toIdMapNodeDTO(IdRelation idRelation) {
        if (Objects.isNull(idRelation)) {
            return null;
        }
        IdMapNodeDTO idMapNodeDTO = new IdMapNodeDTO();
        idMapNodeDTO.setOldId(idRelation.getOldId());
        idMapNodeDTO.setNewId(idRelation.getNewId());
        return idMapNodeDTO;
    }
}
    